<?php
/**
 * 通过命令行运行这个脚本
 *      通过浏览器运行脚本不能即时获取客户端发送的消息
 * 使用`telnet 127.0.0.1 90002`作为客户端
 */
set_time_limit(0);
ob_implicit_flush();

$address = '127.0.0.1';
$port = 90002;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$sock ? success("socket_create") : error("socket_create failed");
socket_bind($sock, $address, $port) ? success("socket_bind") : error("socket_bind failed",$sock);
socket_listen($sock, 5) ? success("socket_listen") : error("socket_listen failed",$sock);

do {
    if (($msgsock = socket_accept($sock))){
        success("socket_accept");
    }
    else{
        error("socket_accept failed",$sock,false);
        break;
    }
    $msg = "\r\nWelcome to the PHP Test Server. \r\nTo quit, type 'quit'. To shut down the server type 'shutdown'.\r\n";
    socket_write($msgsock, $msg, strlen($msg));
    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            error("socket_read failed",$msgsock,false);
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            success("quit");
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            success("shutdown");
            break 2;
        }
        echo "socket_read:'$buf'\r\n";
        $talkback = "back:'$buf'.\r\n";
        socket_write($msgsock, $talkback, strlen($talkback));
    } while (true);
    socket_close($msgsock);
} while (true);
socket_close($sock);


function success($message)
{
    echo "message:$message.\r\n";
}
function error($message,$sock=null,$quit=true)
{
    $error=socket_last_error($sock);
    $reason=socket_strerror($error);
    echo "message:$message.\r\n";
    echo "error:$error.\r\n";
    echo "reason:$reason.\r\n";
    echo "\r\n";
    if($quit) quit($sock);
}
function quit($sock=null)
{
    if($sock) socket_close($sock);
    exit;
}

?>
